package com.warmlight.voicepacket.plugin;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.luck.picture.lib.tools.ScreenUtils;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.activity.VideoDetailsActivity;
import com.warmlight.voicepacket.db.SharePreferenceUtil;
import com.warmlight.voicepacket.db.SharedPerfenceConstant;
import com.warmlight.voicepacket.utils.ActivityUtil;
import com.warmlight.voicepacket.utils.Log;

import java.lang.reflect.Constructor;
import java.util.LinkedHashMap;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by weiweijinpeng on 2018/7/25.
 * 自定义播放器
 */

public abstract class QmzbVideoPlayer extends FrameLayout implements SeekBar.OnSeekBarChangeListener, View.OnClickListener,View.OnTouchListener{

    public static final int SCREEN_WINDOW_NORMAL = 0;
    public static final int SCREEN_WINDOW_LIST = 1;
    public static final int SCREEN_WINDOW_FULLSCREEN = 2;
    public static final int SCREEN_WINDOW_TINY = 3;

    public static final int CURRENT_STATE_NORMAL = 0;
    public static final int CURRENT_STATE_PREPARING = 1;
    public static final int CURRENT_STATE_PREPARING_CHANGING_URL = 2;
    public static final int CURRENT_STATE_PLAYING = 3;
    public static final int CURRENT_STATE_PAUSE = 5;
    public static final int CURRENT_STATE_AUTO_COMPLETE = 6;
    public static final int CURRENT_STATE_ERROR = 7;

    public static final String URL_KEY_DEFAULT = "URL_KEY_DEFAULT";//当播放的地址只有一个的时候的key
    public static final int VIDEO_IMAGE_DISPLAY_TYPE_FILL_PARENT = 1;
    public static final int VIDEO_IMAGE_DISPLAY_TYPE_FILL_SCROP = 2;
    public static final int VIDEO_IMAGE_DISPLAY_TYPE_ORIGINAL = 3;
    public static int VIDEO_IMAGE_DISPLAY_TYPE = 0;

    public static int currentState = -1;
    public int currentScreen = -1;
    public int positionInList = -1;
    public Object[] objects = null;
    public long seekToInAdvance = 0;
    public ViewGroup mViewGroup;
    public int widthRatio = 0;
    public int heightRatio = 0;
    public Object[] dataSourceObjects;//这个参数原封不动直接通过QmzbMeidaManager传给QmzbMediaInterface。
    public int currentUrlMapIndex = 0;
    public int videoRotation = 0;
    protected int mScreenWidth;
    protected int mScreenHeight;
    protected AudioManager mAudioManager;

    protected boolean mTouchingProgressBar;
    public SeekBar progressBar;
    protected long mSeekTimePosition;

    protected boolean mChangePosition;

    protected boolean mChangeVolume;
    protected boolean mChangeBrightness;
    public static int NORMAL_ORIENTATION = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;


    public static final int FULL_SCREEN_NORMAL_DELAY = 300;

    boolean tmp_test_back = false;

    public static long CLICK_QUIT_FULLSCREEN_TIME = 0;

    protected float mDownX;
    protected float mDownY;

    public ViewGroup bottomContainer;
    public ImageView mPlayerView;
    public ImageView fullscreen;
    public TextView currentTimeTextView, totalTimeTextView;

    protected static Timer UPDATE_PROGRESS_TIMER;

    protected ProgressTimerTask mProgressTimerTask;

    private Context mContext;

    public boolean isShowlayout_bottom;


    public QmzbVideoPlayer(Context context) {
        super(context);
        this.mContext=context;
        init(context);
    }

    public QmzbVideoPlayer(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext=context;
        init(context);
    }

    public abstract int getLayoutId();


    public static void releaseAllVideos() {
        if ((System.currentTimeMillis() - CLICK_QUIT_FULLSCREEN_TIME) > FULL_SCREEN_NORMAL_DELAY) {
            QmzbVideoPlayerManager.completeAll();
            QmzbMediaManager.instance().positionInList = -1;
            QmzbMediaManager.instance().releaseMediaPlayer();
        }
    }


    public static void onChildViewAttachedToWindow(View view, int jzvdId) {
        if (QmzbVideoPlayerManager.getCurrentJzvd() != null && QmzbVideoPlayerManager.getCurrentJzvd().currentScreen == QmzbVideoPlayer.SCREEN_WINDOW_TINY) {
            QmzbVideoPlayer videoPlayer = view.findViewById(jzvdId);
            if (videoPlayer != null && VideoPlayerUtils.getCurrentFromDataSource(videoPlayer.dataSourceObjects, videoPlayer.currentUrlMapIndex).equals(QmzbMediaManager.getCurrentDataSource())) {
                QmzbVideoPlayer.backPress();
            }
        }
    }

    public static void onChildViewDetachedFromWindow(View view) {
        if (QmzbVideoPlayerManager.getCurrentJzvd() != null && QmzbVideoPlayerManager.getCurrentJzvd().currentScreen != QmzbVideoPlayer.SCREEN_WINDOW_TINY) {
            QmzbVideoPlayer videoPlayer = QmzbVideoPlayerManager.getCurrentJzvd();
                if (videoPlayer.currentState == QmzbVideoPlayer.CURRENT_STATE_PAUSE) {
                    QmzbVideoPlayer.releaseAllVideos();
                } else {
                    videoPlayer.startWindowTiny();
                }
        }
    }


    public static AudioManager.OnAudioFocusChangeListener onAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {//是否新建个class，代码更规矩，并且变量的位置也很尴尬
        @Override
        public void onAudioFocusChange(int focusChange) {
            switch (focusChange) {
                case AudioManager.AUDIOFOCUS_GAIN:
                    break;
                case AudioManager.AUDIOFOCUS_LOSS:
                    releaseAllVideos();
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                    try {
                        QmzbVideoPlayer player = QmzbVideoPlayerManager.getCurrentJzvd();
                        if (player != null && player.currentState == QmzbVideoPlayer.CURRENT_STATE_PLAYING) {
                            player.mPlayerView.performClick();
                        }
                    } catch (IllegalStateException e) {
                        e.printStackTrace();
                    }
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    break;
            }
        }
    };



    public void init(Context context) {
        View.inflate(context, getLayoutId(), this);
        mViewGroup = findViewById(R.id.surface_container);

        currentTimeTextView = findViewById(R.id.current);
        totalTimeTextView = findViewById(R.id.total);

        bottomContainer = findViewById(R.id.layout_bottom);
        mPlayerView = findViewById(R.id.video_player);
        fullscreen = findViewById(R.id.fullscreen);
        progressBar = findViewById(R.id.bottom_seek_progress);


        bottomContainer.setOnClickListener(this);
        mPlayerView.setOnClickListener(this);
        mPlayerView.setOnTouchListener(this);
        fullscreen.setOnTouchListener(this);
        fullscreen.setOnClickListener(this);
        mViewGroup.setOnClickListener(this);
        mViewGroup.setOnTouchListener(this);
        progressBar.setOnSeekBarChangeListener(this);


        mScreenWidth = getContext().getResources().getDisplayMetrics().widthPixels;
        mScreenHeight = getContext().getResources().getDisplayMetrics().heightPixels;
        mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);

        try {
            if (isCurrentPlay()) {
                NORMAL_ORIENTATION = ((AppCompatActivity) context).getRequestedOrientation();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        float x = event.getX();
        float y = event.getY();
        int id = v.getId();
        if (id == R.id.surface_container) {
            switch (event.getAction()) {

                case MotionEvent.ACTION_DOWN:
                    mTouchingProgressBar = true;
                    mDownX = x;
                    mDownY = y;
                    mChangeVolume = false;
                    mChangePosition = false;
                    mChangeBrightness = false;
                    break;
                case MotionEvent.ACTION_UP:
                    mTouchingProgressBar = false;

                    if (isShowlayout_bottom){
                        bottomContainer.setVisibility(View.GONE);
                    }else{
                        if (bottomContainer.getVisibility() == VISIBLE){
                            bottomContainer.setVisibility(GONE);
                        }else {
                            if (currentState != CURRENT_STATE_NORMAL
                                    && currentState != CURRENT_STATE_ERROR
                                    && currentState != CURRENT_STATE_AUTO_COMPLETE) {
                                post(new Runnable() {
                                    @Override
                                    public void run() {
                                    bottomContainer.setVisibility(View.VISIBLE);
//                                        mPlayerView.setVisibility(View.INVISIBLE);
                                    }
                                });
                            }
//                            bottomContainer.setVisibility(VISIBLE);
                        }
                    }
                    if (isShowlayout_bottom){
                        mPlayerView.setVisibility(GONE);
                    } else {
                        if (mPlayerView.getVisibility() == VISIBLE) {
                            if (currentState != CURRENT_STATE_NORMAL
                                    && currentState != CURRENT_STATE_ERROR
                                    && currentState != CURRENT_STATE_AUTO_COMPLETE) {
                                post(new Runnable() {
                                    @Override
                                    public void run() {
//                                    bottomContainer.setVisibility(View.INVISIBLE);
                                        mPlayerView.setVisibility(View.INVISIBLE);
                                    }
                                });
                            }
                        } else {

                            mPlayerView.setVisibility(View.VISIBLE);
                        }
                    }

                    if (mChangePosition) {
                        QmzbMediaManager.seekTo(mSeekTimePosition);
                        long duration = getDuration();
                        int progress = (int) (mSeekTimePosition * 100 / (duration == 0 ? 1 : duration));
                        progressBar.setProgress(progress);
                    }
                    break;
            }
        }
        return false;
    }


    /**
     * 设置播放器的数据源，
     * @param url
     * @param screen
     * @param objects
     */
    public void setVideoData(String url, int screen, Object... objects) {
        LinkedHashMap map = new LinkedHashMap();
        map.put(URL_KEY_DEFAULT, url);
        Object[] dataSourceObjects = new Object[1];
        dataSourceObjects[0] = map;
        setVideoData(dataSourceObjects, 0, screen, objects);
    }

    public void setVideoData(Object[] dataSourceObjects, int defaultUrlMapIndex, int screen, Object... objects) {

        this.dataSourceObjects = dataSourceObjects;
        this.currentUrlMapIndex = defaultUrlMapIndex;
        this.currentScreen = screen;
        this.objects = objects;
        onStateNormal();
    }

    public void startVideo() {
        QmzbVideoPlayerManager.completeAll();
        initTextureView();
        addTextureView();

        AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
        mAudioManager.requestAudioFocus(onAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
        VideoPlayerUtils.scanForActivity(getContext()).getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        QmzbMediaManager.setDataSource(dataSourceObjects);
        QmzbMediaManager.setCurrentDataSource(VideoPlayerUtils.getCurrentFromDataSource(dataSourceObjects, currentUrlMapIndex));
        QmzbMediaManager.instance().positionInList = positionInList;
        onStatePreparing();
        QmzbVideoPlayerManager.setFirstFloor(this);
    }

    public void onPrepared() {
        onStatePrepared();
        onStatePlaying();
    }
    /**
     * 设置播放器的状态
     */
    public void setState(int state) {
        setState(state, 0, 0);
    }

    public void setState(int state, int urlMapIndex, int seekToInAdvance) {
        switch (state) {
            case CURRENT_STATE_NORMAL:
                onStateNormal();
                break;
            case CURRENT_STATE_PREPARING:
                onStatePreparing();
                break;
            case CURRENT_STATE_PREPARING_CHANGING_URL:
                onStatePreparingChangingUrl(urlMapIndex, seekToInAdvance);
                break;
            case CURRENT_STATE_PLAYING:
                onStatePlaying();
                break;
            case CURRENT_STATE_PAUSE:
                onStatePause();
                break;
            case CURRENT_STATE_ERROR:
                onStateError();
                break;
            case CURRENT_STATE_AUTO_COMPLETE:
                onStateAutoComplete();
                break;
        }
    }

    public void onStateNormal() {
        currentState = CURRENT_STATE_NORMAL;
    }

    public void onStatePreparing() {
        currentState = CURRENT_STATE_PREPARING;
    }

    public void onStatePreparingChangingUrl(int urlMapIndex, long seekToInAdvance) {
        currentState = CURRENT_STATE_PREPARING_CHANGING_URL;
        this.currentUrlMapIndex = urlMapIndex;
        this.seekToInAdvance = seekToInAdvance;
        QmzbMediaManager.setDataSource(dataSourceObjects);
        QmzbMediaManager.setCurrentDataSource(VideoPlayerUtils.getCurrentFromDataSource(dataSourceObjects, currentUrlMapIndex));
        QmzbMediaManager.instance().prepare();
    }

    public void onStatePrepared() {//因为这个紧接着就会进入播放状态，所以不设置state
        if (seekToInAdvance != 0) {
            seekToInAdvance = 0;
            QmzbMediaManager.seekTo(seekToInAdvance);
        } else {
            long position = VideoPlayerUtils.getSavedProgress(getContext(), VideoPlayerUtils.getCurrentFromDataSource(dataSourceObjects, currentUrlMapIndex));
            if (position != 0) {
                QmzbMediaManager.seekTo(position);
            }
        }
    }

    public void onStatePlaying() {
        currentState = CURRENT_STATE_PLAYING;
        startProgressTimer();
    }

    public static boolean isPlaying(){
        return currentState == CURRENT_STATE_PLAYING;
    }

    public static boolean isPause(){
        return currentState == CURRENT_STATE_PAUSE;
    }

    private static boolean isComplete(){
        return currentState == CURRENT_STATE_AUTO_COMPLETE;
    }

    public void onStatePause() {
        currentState = CURRENT_STATE_PAUSE;
        startProgressTimer();
    }

    public void onStateError() {
        currentState = CURRENT_STATE_ERROR;
        startProgressTimer();
    }

    public void onStateAutoComplete() {
        currentState = CURRENT_STATE_AUTO_COMPLETE;
        cancelProgressTimer();
    }

    public void onInfo(int what, int extra) {
    }

    public void onError(int what, int extra) {
        if (what != 38 && extra != -38 && what != -38 && extra != 38 && extra != -19) {
            onStateError();
            if (isCurrentPlay()) {
                QmzbMediaManager.instance().releaseMediaPlayer();
            }
        }
    }

    /**
     * 视频画面绘制
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (currentScreen == SCREEN_WINDOW_FULLSCREEN || currentScreen == SCREEN_WINDOW_TINY) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            return;
        }
        if (widthRatio != 0 && heightRatio != 0) {
            int specWidth = MeasureSpec.getSize(widthMeasureSpec);
            int specHeight = (int) ((specWidth * (float) heightRatio) / widthRatio);
            setMeasuredDimension(specWidth, specHeight);

            int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(specWidth, MeasureSpec.EXACTLY);
            int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(specHeight, MeasureSpec.EXACTLY);
            getChildAt(0).measure(childWidthMeasureSpec, childHeightMeasureSpec);
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }

    public void onAutoCompletion() {
        Runtime.getRuntime().gc();
        onStateAutoComplete();

        if (currentScreen == SCREEN_WINDOW_FULLSCREEN || currentScreen == SCREEN_WINDOW_TINY) {
        }
        QmzbMediaManager.instance().releaseMediaPlayer();
    }

    public void onCompletion() {
        if (currentState == CURRENT_STATE_PLAYING || currentState == CURRENT_STATE_PAUSE) {
            long position = getCurrentPositionWhenPlaying();
        }
        onStateNormal();
        mViewGroup.removeView(QmzbMediaManager.textureView);
        QmzbMediaManager.instance().currentVideoWidth = 0;
        QmzbMediaManager.instance().currentVideoHeight = 0;

        if (QmzbMediaManager.surface != null) QmzbMediaManager.surface.release();
        if (QmzbMediaManager.savedSurfaceTexture != null)
            QmzbMediaManager.savedSurfaceTexture.release();
        QmzbMediaManager.textureView = null;
        QmzbMediaManager.savedSurfaceTexture = null;
    }

    public void initTextureView() {
        removeTextureView();
        QmzbMediaManager.textureView = new QmzbTextureView(getContext());
        QmzbMediaManager.textureView.setSurfaceTextureListener(QmzbMediaManager.instance());
    }

    /**
     * 给布局增加画布
     */
    public void addTextureView() {

        LayoutParams layoutParams =
                new LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        Gravity.CENTER);
        mViewGroup.addView(QmzbMediaManager.textureView, layoutParams);

    }

    public void removeTextureView() {
        QmzbMediaManager.savedSurfaceTexture = null;
        if (QmzbMediaManager.textureView != null && QmzbMediaManager.textureView.getParent() != null) {
            ((ViewGroup) QmzbMediaManager.textureView.getParent()).removeView(QmzbMediaManager.textureView);
        }
    }

    /**
     * 视频属性
     */
    public void onVideoSizeChanged() {
        if (QmzbMediaManager.textureView != null) {
            if (videoRotation != 0) {
                QmzbMediaManager.textureView.setRotation(videoRotation);
            }
            QmzbMediaManager.textureView.setVideoSize(QmzbMediaManager.instance().currentVideoWidth, QmzbMediaManager.instance().currentVideoHeight);
        }
    }


    public static void onPlayOnResume() {
        if (QmzbVideoPlayerManager.getCurrentJzvd() != null) {
            QmzbMediaManager.start();
        }
    }

    public static void onPlayOnPause() {
        if (QmzbVideoPlayerManager.getCurrentJzvd() != null) {
            QmzbMediaManager.pause();
        }
    }

    /**
     * 释放
     * */
    public void releaseVideoPlayer() {
        QmzbMediaManager.pause();
    }

    /**
     * 进度条
     */
    public void startProgressTimer() {
        cancelProgressTimer();
        UPDATE_PROGRESS_TIMER = new Timer();
        mProgressTimerTask = new ProgressTimerTask();
        UPDATE_PROGRESS_TIMER.schedule(mProgressTimerTask, 0, 300);
    }

    public void cancelProgressTimer() {
        if (UPDATE_PROGRESS_TIMER != null) {
            UPDATE_PROGRESS_TIMER.cancel();
        }
        if (mProgressTimerTask != null) {
            mProgressTimerTask.cancel();
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.video_player:
                if (currentState == CURRENT_STATE_NORMAL) {
                    startVideo();
                } else if (currentState == CURRENT_STATE_PLAYING) {
                    QmzbMediaManager.pause();
                    onStatePause();
                    mPlayerView.setImageResource(R.drawable.ic_video_play);
                } else if (currentState == CURRENT_STATE_PAUSE) {
                    QmzbMediaManager.start();
                    onStatePlaying();
                    mPlayerView.setImageResource(R.drawable.ic_video_pause);
                } else if (currentState == CURRENT_STATE_AUTO_COMPLETE) {
                    startVideo();
                }
                ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(mPlayerView, "rotation", 135f, 0f);
                objectAnimator.setDuration(300);
                objectAnimator.start();
                break;
            case  R.id.fullscreen:
                if (currentScreen == SCREEN_WINDOW_FULLSCREEN) {
                    backPress();
                } else {
                    Log.e("点击全屏按钮的状态"+currentState);
                    startWindowFullscreen();
                }
                break;
        }
    }


    /**
     * 设置进度条的视频时长
     * @param progress
     * @param position
     * @param duration
     */
    public void setProgressAndText(int progress, long position, long duration) {
//        Log.d(TAG, "setProgressAndText: progress=" + progress + " position=" + position + " duration=" + duration);
        if (!mTouchingProgressBar) {
            if (progress != 0) progressBar.setProgress(progress);
        }
        if (position != 0) currentTimeTextView.setText(VideoPlayerUtils.stringForTime(position));
        totalTimeTextView.setText(VideoPlayerUtils.stringForTime(duration));
    }

    public void setBufferProgress(int bufferProgress) {
        if (bufferProgress != 0) progressBar.setSecondaryProgress(bufferProgress);
    }

    public void resetProgressAndTime() {
        progressBar.setProgress(0);
        progressBar.setSecondaryProgress(0);
        currentTimeTextView.setText(VideoPlayerUtils.stringForTime(0));
        totalTimeTextView.setText(VideoPlayerUtils.stringForTime(0));
    }

    public long getCurrentPositionWhenPlaying() {
        long position = 0;
        //TODO 这块的判断应该根据MediaPlayer来
        if (currentState == CURRENT_STATE_PLAYING ||
                currentState == CURRENT_STATE_PAUSE) {
            try {
                position = QmzbMediaManager.getCurrentPosition();
            } catch (IllegalStateException e) {
                e.printStackTrace();
                return position;
            }
        }
        return position;
    }

    /**
     * 视频的时长
     * @return
     */
    public long getDuration() {
        long duration = 0;
        //TODO MediaPlayer 判空的问题
//        if (JZMediaManager.instance().mediaPlayer == null) return duration;
        try {
            duration = QmzbMediaManager.getDuration();
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return duration;
        }
        return duration;
    }

    //TODO 是否有用
    public void onSeekComplete() {

    }

    /**
     * 全屏播放
     */

    public void startWindowFullscreen() {
        //获取整个父容器
        ViewGroup vp = (VideoPlayerUtils.scanForActivity(getContext()))//.getWindow().getDecorView();
                .findViewById(Window.ID_ANDROID_CONTENT);
        View old = vp.findViewById(R.id.jz_fullscreen_id);
        if (old != null) {
            vp.removeView(old);
        }
        mViewGroup.removeView(QmzbMediaManager.textureView);
        try {
            Constructor<QmzbVideoPlayer> constructor = (Constructor<QmzbVideoPlayer>) QmzbVideoPlayer.this.getClass().getConstructor(Context.class);
            //设置播放器第二个对象（第二个播放器）
            QmzbVideoPlayer jzVideoPlayer = constructor.newInstance(getContext());

            jzVideoPlayer.setId(R.id.jz_fullscreen_id);

            FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            vp.addView(jzVideoPlayer, lp);

            jzVideoPlayer.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN);

            jzVideoPlayer.setUp(dataSourceObjects, currentUrlMapIndex, QmzbMediaView.SCREEN_WINDOW_FULLSCREEN, objects);
            jzVideoPlayer.setState(currentState);
            jzVideoPlayer.addTextureView();
            QmzbVideoPlayerManager.setSecondFloor(jzVideoPlayer);

//            onStateNormal();
            jzVideoPlayer.progressBar.setSecondaryProgress(progressBar.getSecondaryProgress());
            jzVideoPlayer.startProgressTimer();
            CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 小窗口
     */
    public void startWindowTiny() {
//        if (currentState == CURRENT_STATE_NORMAL || currentState == CURRENT_STATE_ERROR || currentState == CURRENT_STATE_AUTO_COMPLETE)
//            return;
        ViewGroup vp = (VideoPlayerUtils.scanForActivity(getContext()))//.getWindow().getDecorView();
                .findViewById(Window.ID_ANDROID_CONTENT);
        View old = vp.findViewById(R.id.jz_tiny_id);
        if (old != null) {
            vp.removeView(old);
        }
        mViewGroup.removeView(QmzbMediaManager.textureView);

        try {
            Constructor<QmzbVideoPlayer> constructor = (Constructor<QmzbVideoPlayer>) QmzbVideoPlayer.this.getClass().getConstructor(Context.class);
            QmzbVideoPlayer jzVideoPlayer = constructor.newInstance(getContext());
            jzVideoPlayer.setId(R.id.jz_tiny_id);
            FrameLayout.LayoutParams lp;
            if (SharePreferenceUtil.getInstance(mContext).getString(SharedPerfenceConstant.VIDEOSTATUS).equals(VideoDetailsActivity.VIDEO_HORIZONTAL)){
                lp = new FrameLayout.LayoutParams(ActivityUtil.getWidth(mContext)/2, 200);

            }else{
                lp = new FrameLayout.LayoutParams(ActivityUtil.getWidth(mContext)/3, 350);

            }
            // 设置偏移
            com.warmlight.voicepacket.utils.Log.e("高"+ActivityUtil.getStatusHeight(mContext));
            lp.topMargin = ScreenUtils.dip2px(mContext,45)+ ActivityUtil.getStatusHeight(mContext);
            lp.gravity = Gravity.RIGHT | Gravity.TOP;
            vp.addView(jzVideoPlayer, lp);

            jzVideoPlayer.setUp(dataSourceObjects, currentUrlMapIndex, QmzbMediaView.SCREEN_WINDOW_TINY, objects);
            jzVideoPlayer.setState(currentState);
            jzVideoPlayer.addTextureView();
            QmzbVideoPlayerManager.setSecondFloor(jzVideoPlayer);

            jzVideoPlayer.progressBar.setSecondaryProgress(progressBar.getSecondaryProgress());
            jzVideoPlayer.startProgressTimer();
            CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();

//            onStateNormal();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void setUp(String url, int screen, Object... objects) {
        LinkedHashMap map = new LinkedHashMap();
        map.put(URL_KEY_DEFAULT, url);
        Object[] dataSourceObjects = new Object[1];
        dataSourceObjects[0] = map;
        setUp(dataSourceObjects, 0, screen, objects);
    }

    public void setUp(Object[] dataSourceObjects, int defaultUrlMapIndex, int screen, Object... objects) {
        if (this.dataSourceObjects != null && VideoPlayerUtils.getCurrentFromDataSource(dataSourceObjects, currentUrlMapIndex) != null &&
                VideoPlayerUtils.getCurrentFromDataSource(this.dataSourceObjects, currentUrlMapIndex).equals(VideoPlayerUtils.getCurrentFromDataSource(dataSourceObjects, currentUrlMapIndex))) {
            return;
        }
        if (isCurrentJZVD() && VideoPlayerUtils.dataSourceObjectsContainsUri(dataSourceObjects, QmzbMediaManager.getCurrentDataSource())) {
            long position = 0;
            try {
                position = QmzbMediaManager.getCurrentPosition();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
            if (position != 0) {
                VideoPlayerUtils.saveProgress(getContext(), QmzbMediaManager.getCurrentDataSource(), position);
            }
            QmzbMediaManager.instance().releaseMediaPlayer();
        } else if (isCurrentJZVD() && !VideoPlayerUtils.dataSourceObjectsContainsUri(dataSourceObjects, QmzbMediaManager.getCurrentDataSource())) {
            startWindowTiny();
        } else if (!isCurrentJZVD() && VideoPlayerUtils.dataSourceObjectsContainsUri(dataSourceObjects, QmzbMediaManager.getCurrentDataSource())) {
            if (QmzbVideoPlayerManager.getCurrentJzvd() != null &&
                    QmzbVideoPlayerManager.getCurrentJzvd().currentScreen == QmzbVideoPlayer.SCREEN_WINDOW_TINY) {
                //需要退出小窗退到我这里，我这里是第一层级
                tmp_test_back = true;
            }
        } else if (!isCurrentJZVD() && !VideoPlayerUtils.dataSourceObjectsContainsUri(dataSourceObjects, QmzbMediaManager.getCurrentDataSource())) {
        }
        this.dataSourceObjects = dataSourceObjects;
        this.currentUrlMapIndex = defaultUrlMapIndex;
        this.currentScreen = screen;
        this.objects = objects;
//        onStateNormal();
        Log.e("setUp结束的状态"+currentState);

    }


    /**
     * 退出全屏状态
     * @return
     */
    public static boolean backPress() {
        if ((System.currentTimeMillis() - CLICK_QUIT_FULLSCREEN_TIME) < FULL_SCREEN_NORMAL_DELAY)
            return false;

        if (QmzbVideoPlayerManager.getSecondFloor() != null) {
            CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();
            if (VideoPlayerUtils.dataSourceObjectsContainsUri(QmzbVideoPlayerManager.getFirstFloor().dataSourceObjects, QmzbMediaManager.getCurrentDataSource())) {
                QmzbVideoPlayer jzVideoPlayer = QmzbVideoPlayerManager.getSecondFloor();
//                jzVideoPlayer.onEvent(jzVideoPlayer.currentScreen == QmzbMediaView.SCREEN_WINDOW_FULLSCREEN ?
//                        JZUserAction.ON_QUIT_FULLSCREEN :
//                        JZUserAction.ON_QUIT_TINYSCREEN);
                QmzbVideoPlayerManager.getFirstFloor().playOnThisJzvd();
            } else {
                quitFullscreenOrTinyWindow();
            }
            return true;
        } else if (QmzbVideoPlayerManager.getFirstFloor() != null &&
                (QmzbVideoPlayerManager.getFirstFloor().currentScreen == SCREEN_WINDOW_FULLSCREEN ||
                        QmzbVideoPlayerManager.getFirstFloor().currentScreen == SCREEN_WINDOW_TINY)) {//以前我总想把这两个判断写到一起，这分明是两个独立是逻辑
            CLICK_QUIT_FULLSCREEN_TIME = System.currentTimeMillis();
            quitFullscreenOrTinyWindow();
            return true;
        }
        return false;
    }

    public static void quitFullscreenOrTinyWindow() {
        //直接退出全屏和小窗
        QmzbVideoPlayerManager.getFirstFloor().clearFloatScreen();
        QmzbMediaManager.instance().releaseMediaPlayer();
        QmzbVideoPlayerManager.completeAll();
    }

    //退出全屏和小窗的方法
    public void playOnThisJzvd() {
        //1.清空全屏和小窗的jzvd
        currentState = QmzbVideoPlayerManager.getSecondFloor().currentState;
        currentUrlMapIndex = QmzbVideoPlayerManager.getSecondFloor().currentUrlMapIndex;

        clearFloatScreen();

        //2.在本jzvd上播放
        setState(currentState);
//        removeTextureView();
        addTextureView();
    }

    public void clearFloatScreen() {

        VideoPlayerUtils.setRequestedOrientation(getContext(), NORMAL_ORIENTATION);
        final ViewGroup vp = (VideoPlayerUtils.scanForActivity(getContext()))//.getWindow().getDecorView();
                .findViewById(Window.ID_ANDROID_CONTENT);
        QmzbVideoPlayer fullJzvd = vp.findViewById(R.id.jz_fullscreen_id);
        final QmzbVideoPlayer tinyJzvd = vp.findViewById(R.id.jz_tiny_id);

        if (fullJzvd != null) {
            vp.removeView(fullJzvd);
            if (fullJzvd.mViewGroup != null)
                fullJzvd.mViewGroup.removeView(QmzbMediaManager.textureView);
        }

        if (tinyJzvd != null) {
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    vp.removeView(tinyJzvd);
                }
            });

            if (tinyJzvd.mViewGroup != null){
                tinyJzvd.mViewGroup.removeView(QmzbMediaManager.textureView);
            }

        }
        QmzbVideoPlayerManager.setSecondFloor(null);

    }

    /**
     * 播放进度条拖动
     * @param seekBar
     */
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        cancelProgressTimer();
        ViewParent vpdown = getParent();
        while (vpdown != null) {
            vpdown.requestDisallowInterceptTouchEvent(true);
            vpdown = vpdown.getParent();
        }
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        startProgressTimer();
        ViewParent vpup = getParent();
        while (vpup != null) {
            vpup.requestDisallowInterceptTouchEvent(false);
            vpup = vpup.getParent();
        }
        if (currentState != CURRENT_STATE_PLAYING &&
                currentState != CURRENT_STATE_PAUSE) return;
        long time = seekBar.getProgress() * getDuration() / 100;
        QmzbMediaManager.seekTo(time);
    }


    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (fromUser) {
            //设置这个progres对应的时间，给textview
            long duration = getDuration();
            currentTimeTextView.setText(VideoPlayerUtils.stringForTime(progress * duration / 100));
        }
    }


    public boolean isCurrentPlay() {
        return isCurrentJZVD()
                && VideoPlayerUtils.dataSourceObjectsContainsUri(dataSourceObjects, QmzbMediaManager.getCurrentDataSource());//不仅正在播放的url不能一样，并且各个清晰度也不能一样
    }

    public boolean isCurrentJZVD() {
        return QmzbVideoPlayerManager.getCurrentJzvd() != null
                && QmzbVideoPlayerManager.getCurrentJzvd() == this;
    }

    public void showProgressDialog(float deltaX,
                                   String seekTime, long seekTimePosition,
                                   String totalTime, long totalTimeDuration) {
    }

    public class ProgressTimerTask extends TimerTask {

        @Override
        public void run() {
            if (currentState == CURRENT_STATE_PLAYING || currentState == CURRENT_STATE_PAUSE) {
                post(new Runnable() {
                    @Override
                    public void run() {
                        long position = getCurrentPositionWhenPlaying();
                        long duration = getDuration();
                        int progress = (int) (position * 100 / (duration == 0 ? 1 : duration));
                        setProgressAndText(progress, position, duration);
                    }
                });
            }
        }
    }

}
